<template>
  <div class="app-container">
    <div style="margin-bottom: 55px;">
      <el-row>
        <el-card shadow="never">
          <el-row style="display: flex; align-items: center;">
            <el-col :span="2">
              <el-button style="fpadding: 3px 0" type="text" icon="el-icon-arrow-left" size="small" @click="back">返回</el-button>
            </el-col>
            <el-col :span="18">
              <el-tag type="primary" effect="dark"  style="margin-right: 20px">业务结算单开票</el-tag>
              <strong>{{detailForm.orderNo}}</strong>
              <el-divider direction="vertical"></el-divider>
              <span>时间：{{detailForm.settleTime}}</span>
              <el-divider direction="vertical"></el-divider>
              <span>单据状态: </span>
              <el-link type="success" :underline="false"><i class="el-icon-circle-check"></i>{{detailForm.settlebillStatusName}}</el-link>
              <el-divider direction="vertical"></el-divider>
            </el-col>
          </el-row>
        </el-card>
      </el-row>
      <el-row style="padding-top: 10px" class="v-deep">
        <el-col :span="24" :xs="24">
          <el-collapse v-model="activeNames2">
            <el-collapse-item name="1">
              <template slot="title">
                <div>主体信息</div>
              </template>
              <div style="padding: 5px">
                <el-descriptions :column="4" size="small" border>
                  <el-descriptions-item label="形式发票类型">
                    <el-tag v-if="detailForm.natureType == 'C'" type="danger">{{detailForm.natureTypeName}}</el-tag>
                    <el-tag v-else >{{detailForm.natureTypeName}}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="发票类型">{{detailForm.invoiceTypeName}}</el-descriptions-item>
                  <el-descriptions-item label="应用于发票号">{{detailForm.sourceOrderNo}}</el-descriptions-item>
                  <el-descriptions-item label="开票人">{{detailForm.invoiceName}}</el-descriptions-item>

                  <el-descriptions-item label="账单条款">{{detailForm.termsCodeName}}</el-descriptions-item>
                  <el-descriptions-item label="币别">{{detailForm.currencyName}}</el-descriptions-item>
                  <el-descriptions-item label="汇率">{{detailForm.exchRate}}</el-descriptions-item>
                  <el-descriptions-item label="来源">{{detailForm.postFromCoName}}</el-descriptions-item>

                  <el-descriptions-item label="购方名称">{{detailForm.buyerName}}</el-descriptions-item>
                  <el-descriptions-item label="购方纳税识别号">{{detailForm.buyerNumber}}</el-descriptions-item>
                  <el-descriptions-item label="购方电话">{{detailForm.buyerTel}}</el-descriptions-item>
                  <el-descriptions-item label="购方地址">{{detailForm.buyerAddress}}</el-descriptions-item>
                  <el-descriptions-item label="购方开户行">{{detailForm.buyerBank}}</el-descriptions-item>
                  <el-descriptions-item label="购方账号">{{detailForm.buyerAccount}}</el-descriptions-item>
                  <el-descriptions-item label=""></el-descriptions-item>
                  <el-descriptions-item label=""></el-descriptions-item>

                  <el-descriptions-item label="销方名称">{{detailForm.sellerName}}</el-descriptions-item>
                  <el-descriptions-item label="销方纳税识别号">{{detailForm.sellerNumber}}</el-descriptions-item>
                  <el-descriptions-item label="销方电话">{{detailForm.sellerTel}}</el-descriptions-item>
                  <el-descriptions-item label="销方地址">{{detailForm.sellerAddress}}</el-descriptions-item>
                  <el-descriptions-item label="销方开户行">{{detailForm.sellerBank}}</el-descriptions-item>
                  <el-descriptions-item label="销方账号">{{detailForm.sellerAccount}}</el-descriptions-item>
                  <el-descriptions-item label=""></el-descriptions-item>
                  <el-descriptions-item label=""></el-descriptions-item>

                  <el-descriptions-item label="收款人">{{detailForm.collectName}}</el-descriptions-item>
                  <el-descriptions-item label="收票人邮箱">{{detailForm.collectMail}}</el-descriptions-item>
                  <el-descriptions-item label="收票人手机号">{{detailForm.collectMobile}}</el-descriptions-item>

                  <el-descriptions-item label="税日期">{{detailForm.taxDate}}</el-descriptions-item>
                  <el-descriptions-item label="到期日期">{{detailForm.dueDate}}</el-descriptions-item>
                  <el-descriptions-item label="发货日期">{{detailForm.deliveryTime}}</el-descriptions-item>
                  <el-descriptions-item label="结算日期">{{detailForm.settleTime}}</el-descriptions-item>

                  <el-descriptions-item label="商品总金额"><strong>¥{{detailForm.amount | formatCurrency}}</strong></el-descriptions-item>
                  <el-descriptions-item label="运费"><strong>¥{{detailForm.freightFee}}</strong></el-descriptions-item>
                  <el-descriptions-item label="杂费"><strong>¥{{detailForm.miscChargesFee}}</strong></el-descriptions-item>
                  <el-descriptions-item label="税额"><strong>¥{{detailForm.tax | formatCurrency}}</strong></el-descriptions-item>
                  <el-descriptions-item label="金额(不含税)"><strong>¥{{detailForm.feeWithoutTax | formatCurrency }}</strong></el-descriptions-item>
                  <el-descriptions-item label="金额(含税)"><strong>¥{{detailForm.fee | formatCurrency}}</strong></el-descriptions-item>
                  <el-descriptions-item label="备注">{{detailForm.remark}}</el-descriptions-item>
                </el-descriptions>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>
      <el-row style="padding-top: 10px" class="v-deep">
        <el-col :span="24" :xs="24">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="1" >
              <template slot="title">
                <div>开票明细</div>
              </template>
              <div style="padding: 5px" class="low-height-th-table">
                <el-table
                  border
                  stripe
                  default-expand-all
                  ref="tableRef"
                  v-loading="loading"
                  :data="settlebillEntryList"
                  :header-cell-style= "{
                    'font-size': '12px !important',
                    'font-weight': '500 !important',
                    'color':'#FFF',
                    'background-color':'rgb(51 112 255 / 80%)',
                    textAlign: 'left',
                    'height': '30px !important'
                  }"
                  :cell-style="{ padding: '8px 10px 8px 0', textAlign: 'left' }"
                  highlight-current-row style="width: 100%;"
                  height="450px"
                >
                  <el-table-column label="序号" align="center" prop="index" width="70" fixed="left">
                    <template slot-scope="scope">{{scope.$index+1}}</template>
                  </el-table-column>
                  <el-table-column label="物料" align="left" prop="productName" width="150" show-overflow-tooltip>
                    <template slot-scope="scope">{{scope.row.productName}} | {{scope.row.productCode}} </template>
                  </el-table-column>
                  <el-table-column label="规格型号" align="left" prop="specificatCode" width="120" show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column label="单位" align="left" prop="unit" width="80"  show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column label="开票产品" align="left" prop="kpProductName" width="240" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.kpProductCode" size="small" v-if="scope.row.productList" clearable filterable @change="selectKpProductChange(scope.row)" style="width:160px">
                        <el-option
                          v-for="product in scope.row.productList"
                          :key="product.productCode"
                          :label="product.productName + '(' + product.taxRateName + ')'"
                          :value="product.productCode"
                        ></el-option>
                      </el-select>
                      <el-button type="primary" style="margin-left: 10px" size="mini" v-if="scope.row.productList" @click="refreshProductList(scope.row)" icon="el-icon-search"></el-button>
                      <span v-if="!scope.row.productList">  {{scope.row.kpProduct ? scope.row.kpProduct.productName : ''}} </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="开票产品编码" align="left" prop="kpProductCode" width="180" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span> {{scope.row.kpProduct ? scope.row.kpProduct.productCode : ''}} </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="税收分类名称" align="left" prop="kpProductTaxName" width="220" show-overflow-tooltip>

                  </el-table-column>
                  <el-table-column label="税收分类编码" align="left" prop="kpProductTaxCode" width="220" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <strong> {{scope.row.kpProductTaxCode}} </strong>
                    </template>
                  </el-table-column>
                  <el-table-column label="单位" align="left" prop="kpProductUnit" width="80" show-overflow-tooltip>

                  </el-table-column>
                  <el-table-column label="开票产品税率" align="left" prop="kpProductTax" width="100" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{scope.row.kpProductTax ? scope.row.kpProductTax : '-'}}%
                    </template>
                  </el-table-column>
                  <el-table-column label="单价(含税)" align="right" prop="price" width="120"  show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column label="开票数量" align="left" prop="qty" width="100"  show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column label="开票金额(不含税)" align="right" prop="withoutAmount" width="130"  show-overflow-tooltip >
                  </el-table-column>
                  <el-table-column label="开票金额(含税)" align="right" prop="amount" width="130" show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column label="税额" align="left" prop="tax"  width="130">
                  </el-table-column>
                  <el-table-column label="订单号" align="right" prop="orderNo" width="140"  show-overflow-tooltip>
                  </el-table-column>
                  <div slot="empty">
                    <svg-icon icon-class="search-none" style="font-size: 64px;" />
                    <p>暂无数据，请添加明细</p>
                  </div>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>

    </div>
    <div style="position: fixed;z-index: 999;bottom: 0px;width: 100%;margin-top: 16px;box-shadow: rgba(0, 0, 0, 0.15) 0px 2px 12px 4px;">
      <div style="display: flex;height: 56px;background-color: #FFFF;">
        <div style="width: 100px;padding: 15px 28px;background-color: #3370ff;color: #FFF;font-size: 20px;font-weight: 600;">
          <span>合计</span>
        </div>
        <div style="display: flex;flex-grow: 1;align-items: center;">
          <div style="width: 400px;padding: 0 15px;">
            <svg-icon icon-class="money" style="color: rgb(255, 88, 88);    font-size: 18px;"/> 金额(不含税)
            <span style="font-weight: 800; margin-left: 5px">
              ¥{{detailForm.feeWithoutTax | formatCurrency}}
            </span>

          </div>
          <div style="width: 350px;padding: 0 15px;">
            <svg-icon icon-class="rmb1" style="color: rgb(255, 165, 71);    font-size: 18px;"/>  金额(含税)
            <span style="font-weight: 800; margin-left: 5px">
              ¥{{detailForm.fee | formatCurrency}}
            </span>
          </div>
          <div style="width: 300px;padding: 0 15px;">
            <svg-icon icon-class="zonge" style="color: rgb(41, 180, 240);    font-size: 18px;" />  税额
            <span style="font-weight: 800; margin-left: 5px">
              ¥{{detailForm.tax | formatCurrency}}
            </span>
          </div>
          <div style="width: 300px;padding: 0 15px;">
            <el-button type="primary" style="float: right;margin-left: 10px" @click="saveAsInvoice" :disabled="unableSave">确 认</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 查看发票 -->
    <el-dialog v-dialogDrag  :close-on-click-modal="false" title="查看发票" :visible.sync="invoiceOpen" width="1400px" append-to-body>
      <div class="dialog_box" style="height:650px;">
        <el-row>
          <el-col :span="10">
            <div style="height:575px; overflow-y: auto">
              <el-tabs type="border-card">
                <el-tab-pane label="发票信息">
                  <el-descriptions class="margin-top" title="基本信息" :column="2" size="mini" border>
                    <template slot="title">
                      <div>基本信息 <span class="invoice-type">{{detailForm.invoiceTypeName}}</span></div>
                    </template>
                    <el-descriptions-item>
                      <template slot="label">
                        发票代码：
                      </template>
                      {{detailForm.invoiceCode}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        发票号码：
                      </template>
                      {{detailForm.invoiceNo}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        开票日期：
                      </template>
                      {{detailForm.invoiceDate}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        金额(不含税):
                      </template>
                      ¥{{detailForm.feeWithoutTax}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        税额:
                      </template>
                      ¥{{detailForm.tax}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        金额(含税):
                      </template>
                      ¥{{detailForm.fee}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        校验码:
                      </template>
                      {{detailForm.checkCode}}
                    </el-descriptions-item>
                  </el-descriptions>

                  <el-descriptions class="margin-top" title="抬头信息" :column="1" size="mini" border>
                    <template slot="extra">
                      <el-radio-group v-model="isWithout" size="mini">
                        <el-radio-button label="销方"></el-radio-button>
                        <el-radio-button label="购方"></el-radio-button>
                      </el-radio-group>
                    </template>
                    <el-descriptions-item>
                      <template slot="label">
                        名称:
                      </template>
                      {{detailForm.name}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        纳税识别号:
                      </template>
                      {{detailForm.buyerNumber}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        地址、电话:
                      </template>
                      {{detailForm.buyerAddress}}-{{detailForm.buyerTel}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        开户行及账号:
                      </template>
                      {{detailForm.buyerBank}}-{{detailForm.buyerAccount}}
                    </el-descriptions-item>
                  </el-descriptions>

                  <el-descriptions class="margin-top" title="业务信息" :column="2" size="mini" border>

                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        发货日期:
                      </template>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        特殊开票:
                      </template>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        开票网点:
                      </template>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        站点:
                      </template>
                    </el-descriptions-item>
                  </el-descriptions>
                  <el-descriptions class="margin-top" title="商品明细" :column="1" size="mini" border >
                    <template slot="extra">
                      <el-radio-group v-model="isWithout" size="mini">
                        <el-radio-button label="含税"></el-radio-button>
                        <el-radio-button label="不含税"></el-radio-button>
                      </el-radio-group>
                    </template>
                    <el-descriptions-item>
                      <el-table
                        border
                        stripe
                        default-expand-all
                        ref="invoiceDetailEntry"
                        v-loading="loading"
                        :data="settlebillEntryList"
                        :header-cell-style= "{
                          'font-size': '12px !important',
                          'font-weight': '500 !important',
                          'color':'#FFF',
                          'padding': '0px 0',
                          'background-color':'rgb(51 112 255 / 80%)',
                          textAlign: 'left',
                          'height': '30px !important'
                        }"
                        :cell-style="{ padding: '8px 10px 8px 0', textAlign: 'left' }"
                        highlight-current-row
                        style="width: 555px;margin-left: -32px;margin-top: -10px;"
                        height="400px"
                      >
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column label="序号" align="center" prop="index" width="70">
                          <template slot-scope="scope">{{scope.$index+1}}</template>
                        </el-table-column>
                        <el-table-column label="产品名称" align="left" prop="productName" width="250">
                        </el-table-column>
                        <el-table-column label="税编简称" align="left" prop="taxShortName" width="180">
                        </el-table-column>
                        <el-table-column label="规格型号" align="left" prop="specificatCode" width="120" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column label="单位" align="left" prop="unit" width="80">
                        </el-table-column>
                        <el-table-column label="数量" align="left" prop="qty" width="100">
                        </el-table-column>
                        <el-table-column label="单价(不含税)" align="right" prop="withoutPrice"  width="120" >
                        </el-table-column>
                        <el-table-column label="金额(不含税)" align="right" prop="withoutAmount" width="120"  >
                        </el-table-column>
                        <el-table-column label="单价(含税)" align="right" prop="price" width="120" >
                        </el-table-column>
                        <el-table-column label="金额(含税)" align="right" prop="amount" width="120">
                        </el-table-column>
                        <el-table-column label="折扣金额(不含税)" align="right" prop="withoutDiscountAmount" width="160"  >
                        </el-table-column>
                        <el-table-column label="折扣金额(含税)" align="right" prop="discountAmount" width="160">
                        </el-table-column>
                        <el-table-column label="税率" align="left" prop="taxRate"  width="140">
                        </el-table-column>
                        <el-table-column label="税额" align="right" prop="tax"  width="120">
                        </el-table-column>
                        <div slot="empty">
                          <svg-icon icon-class="search-none" style="font-size: 64px;" />
                          <p>暂无数据</p>
                        </div>
                      </el-table>
                    </el-descriptions-item>

                  </el-descriptions>


                </el-tab-pane>
              </el-tabs>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 产品查询-弹出查询 -->
    <el-dialog v-dialogDrag  :close-on-click-modal="false" title="选择物料" :visible.sync="searchProductCodeDialogOpen" width="1000px" append-to-body>
      <div class="dialog_box" style="height:550px;">
        <el-form label-position="left" :model="searchProductCodeQueryParams" :inline="true"  ref="searchProductCodeQueryForm" label-width="88px" >
          <el-form-item  prop="searchProductCodeSearchValue">
            <el-input
              v-model="searchProductCodeQueryParams.searchValue"
              size="mini"
              placeholder="请输入物料名称查询"
              @keyup.enter.native="handleSearchProductCodeQuery"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearchProductCodeQuery">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="searchProductCodeSelectLoading" :data="searchProductCodeList"
                  height="450"
                  @row-click="handleSearchProductCodeRowClick"
                  ref="searchProductCodeSingleTable"
                  :row-key="getSearchProductCodeListRowKey"
                  :row-style="{height:2+'px'}"
                  :header-cell-style= "{
                        'font-size': '14px !important',
                        'font-weight': '500 !important',
                        'background-color':'rgb(241 241 241 / 52%)'
                      }"
                  :cell-style="{padding:'2px 4px'}"
                  border
                  @selection-change="handleSearchProductCodeSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <!-- 数据 -->
          <el-table-column label="序号" align="left" prop="index" width="70">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="productName" label="物料名称" show-overflow-tooltip></el-table-column>
          <el-table-column label="规格型号" align="left" prop="specificatCode" width="120" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="待拆数量"  align="left" prop="qty"  width="120"></el-table-column>
          <el-table-column label="单位" align="left" prop="unit" width="100">
          </el-table-column>
          <el-table-column prop="price" label="单价"  width="100" align="right"></el-table-column>
          <el-table-column prop="amount" label="待拆金额"  width="120" align="right"></el-table-column>
          <!--          <el-table-column label="税率" align="left" prop="taxRate"  width="80">-->
          <!--            <template slot-scope="scope">-->
          <!--              {{scope.row.taxRate ?  (scope.row.taxRate+'%') : ''}}-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <!--          <el-table-column prop="tax" label="税额"  align="right"></el-table-column>-->
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="confirmSearchProductCode">确 定</el-button>
        <el-button size="mini"   @click="searchProductCodeCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>

</template>
<style lang="scss">
  .input_num .el-input__inner{
    padding: 0 0 0 15px !important;
    color: red;
    font-weight: 700;
  }
  .el-table .warning-row {
    background: oldlace;
  }
  .el-table .success-row {
    background: #f0f9eb;
  }
  .el-card__body, .el-main {
    padding: 5px 20px !important;
  }

  .collapse-title{
    background-color: red;
  }
  .el-collapse-item__header.is-active {
    border-bottom: 1px solid #f0f2f5 !important;
  }
  .el-collapse-item__header::before{
    content: "";
    display: block;
    width: 3px;
    height: 20px;
    position: absolute;
    background-color: #297cf0;
    left: 0px;
    top: 35px;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
  }

  .el-collapse-item__header div{
    margin-left: 10px;
  }
  .el-form-item__label{
    margin-bottom: -12px;
  }

  .v-deep{
    .el-collapse-item__arrow {
      width: 40px;
    }
    .el-icon-arrow-right:before {
      content: "展开";
      font-size: 14px;
      font-family: 'heiti';
      color: #2295ff;
    }
    .el-collapse-item__arrow.is-active {
      transform: none;
    }
    .el-collapse-item__arrow.is-active::before {
      content: "收起";
      font-size: 14px;
      font-family: 'heiti';
      color: #2295ff;
    }
    .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
      margin-bottom: 8px;
    }
  }

  .el-descriptions__header{
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    margin-bottom: 5px !important;
    margin-top: 5px;
  }
  .el-descriptions__title::before{
    content: "";
    display: block;
    width: 3px;
    height: 20px;
    position: absolute;
    background-color: #297cf0;
    left: 0px;
    margin-top: 11px;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
  }
  .invoice-type {
    font-size: 12px;
    font-weight: 500;
    border: 2px solid;
    padding: 2px 6px;
    color: hsl(158deg 86% 34%);
    border-radius: 4px;
  }
  .invoice-type::before,
  .invoice-type::after {
    position: absolute;
    content: '';
    width: 6px;
    height: 6px;
    background-color: #fff;
    border: 2px solid hsl(158deg 86% 34%);
    border-left-color: transparent;
    border-bottom-color: transparent;
    border-radius: 50%;
    margin-top: 10px;
  }

  .invoice-type::before {
    margin-left: -10px;
    transform: rotate(45deg);
  }

  .invoice-type::after {
    margin-left: 3px;
    transform: rotate(-135deg);
  }

</style>

<script>
    import { listSettlebill, getByIdForInvoice, delSettlebill, addSettlebill, updateSettlebill, saveAsSalInvoice } from "@/api/doc/settlebill";
    import { getProductListByMaterialCode } from "@/api/saleconfig/product";


    import Viewer from 'v-viewer';
    export default {
        name: "SettleBillMake",
        dicts: ['invoice_type', 'collection_type', 'business_type', 'tax_rate'],
        data() {
            return {
                settleId: null,
                activeNames: ['1'],
                activeNames2: ['1'],
                detailForm:{
                    fee:0
                },
                loading:false,
                settlebillEntryList:[],
                allSettlebillEntryList:[],
                tobeSettlebillEntryList:[],
                productList:[],
                isWithout:'含税',
                invoiceOpen:false,
                options:{
                    zIndex: 99999,
                    inline: true,
                    button: true,
                    navbar: true,
                    title: true,
                    toolbar: true,
                    tooltip: true,
                    movable: true,
                    zoomable: true,
                    rotatable: true,
                    scalable: true,
                    transition: true,
                    fullscreen: false,
                    keyboard: true,
                    url: 'data-source'
                },

                /* ======================================查询条件-明细选择======================================  */
                searchProductCodes:[],
                searchProductNames:[],
                searchProductCodeTotal: 0,
                searchProductCodeList: [],
                searchProductCodeDialogOpen: false,
                searchProductCodeSelectLoading: false,
                searchProductCodeQueryParams: {
                    searchValue: null,
                    pageNum: 1,
                    pageSize: 20,
                },
                unableSave: false
            };
        },
        created() {
            // 获取发票ID
            this.settleId = this.$route.params && this.$route.query.settleId;
            console.log("获取结算单ID：" + this.settleId);
            this.init(this.settleId);
        },
        methods: {
            /** 初始化 **/
            init(settleId){
                this.$modal.loading("正在初始化，请稍候...");
                this.detailForm = { fee:0 };
                this.settlebillEntryList = [];
                this.allSettlebillEntryList = [];
                this.tobeSettlebillEntryList = [];
                getByIdForInvoice(settleId).then(response => {
                    this.detailForm = response.data;
                    this.allSettlebillEntryList = response.data.tscSettlebillEntryList;

                    // 查询所有产品
                    getProductListByMaterialCode().then(res => {
                        this.productList = res;
                        this.allSettlebillEntryList.forEach(obj => {
                            if(obj){
                               this.addSettlebillEntryToList(obj);
                            }
                        });
                        this.refreshFee();
                        this.$modal.closeLoading();
                    }).catch(() => {
                        return;
                    });

                });


            },
            /** 返回至列表页 */
            back(){
                //关闭当前页
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({path:'/sal/settle/settlebill/'})
            },
            /**
             * 新增拆分明细
             */
            handleAddSettlebillEntry(){
                this.openSearchProductDialogOpen();
            },
            /* ※※ 查询 产品 相关方法 start ※※ */
            /** ① 弹出查询条件-产品 */
            openSearchProductDialogOpen(){
                this.searchProductCodeDialogOpen = true;
                // 默认查询
                this.handleSearchProductCodeQuery();
            },
            /** ② 单击行 **/
            handleSearchProductCodeRowClick(row, column, event){
                this.$refs.searchProductCodeSingleTable.toggleRowSelection(row);
            },
            /** ③ 行KEY **/
            getSearchProductCodeListRowKey(row) {
                return row.id
            },
            /** ④ 选中产品 **/
            handleSearchProductCodeSelectionChange(selection) {
                if(selection){
                    let obj;
                    selection.forEach(item => {
                        obj = this.copyObj(item);
                        this.tobeSettlebillEntryList.push(obj);
                    })
                } else {
                    this.$refs.table.clearSelection();
                }
                this.refreshFee();
            },
            // 添加对象到开票列表
            addSettlebillEntryToList(obj){

                obj.orgQty = obj.qty;
                obj.orgAmount = obj.amount;
                obj.orgWithoutAmount = obj.withoutAmount;
                obj.orgDiscountAmount = obj.discountAmount;
                obj.orgWithoutDiscountAmount = obj.withoutDiscountAmount;

                // 需要页面编辑的字段初始化为0
                // obj.qty = 0;
                // obj.amount = 0;
                // obj.withoutAmount = 0;
                // obj.discountAmount = 0;
                // obj.withoutDiscountAmount = 0;
                obj.productList = this.productList;
                obj.kpProduct = {};
                //
                this.productList.forEach(product => {
                    if(obj.taxCategoryCode && obj.taxCategoryCode === product.taxCode){
                        obj.productList = null;
                        obj.kpProduct = product;
                        obj.kpProductTax = obj.kpProduct.taxRate;
                        obj.kpProductUnit = obj.unit;
                        obj.kpProductTaxName = obj.kpProduct.taxName;
                        obj.kpProductTaxCode = obj.kpProduct.taxCode;
                        // 2.刷新税率，刷新金额
                        // obj.withoutDiscountAmount = Number(obj.discountAmount/((obj.kpProductTax/100)+1)).toFixed(8);
                        // obj.withoutAmount = Number(obj.amount/((obj.kpProductTax/100)+1)).toFixed(8);
                        // obj.tax = Number(obj.amount - obj.withoutAmount).toFixed(8);
                    }
                });
                this.settlebillEntryList.push(obj);

            },
            /** ⑤ 点击查询按钮 **/
            handleSearchProductCodeQuery(){
                this.searchProductCodeQueryParams.pageNum = 1;
                this.getSearchProductCodeList();
            },
            /** ⑥ 查询 **/
            getSearchProductCodeList(){
                let searchProductCodeTempList = new Array();
                let productCodes = ',';
                for(let i= 0; i<this.settlebillEntryList.length; i++){
                    productCodes += this.settlebillEntryList[i].productCode + ',';
                }
                // 取该订单明细，并去除已选择的
                if(this.searchProductCodeQueryParams.searchValue){
                    searchProductCodeTempList = this.allSettlebillEntryList.filter(item =>
                        item.productName.indexOf(this.searchProductCodeQueryParams.searchValue) > -1
                        &&
                        productCodes.indexOf(',' + item.productCode + ',') == -1
                    );
                } else {
                    searchProductCodeTempList = this.allSettlebillEntryList.filter(item =>
                        productCodes.indexOf(',' + item.productCode + ',') == -1
                    );
                }
                this.searchProductCodeList = searchProductCodeTempList;
                this.searchProductCodeTotal = this.searchProductCodeList.length;
            },
            /** ⑦ 点击确认查询 **/
            confirmSearchProductCode() {
                this.$modal.loading("正在加载，请稍候...");
                this.tobeSettlebillEntryList.forEach(obj => {
                    if(obj){
                        // 判重
                        let isRepetitive = false;
                        for(let i=0; i<this.settlebillEntryList.length; i++){
                            if(this.settlebillEntryList[i].id === obj.id){
                                isRepetitive = true;
                                console.warn('重复添加');
                            }
                        }
                        if(!isRepetitive){
                            this.addSettlebillEntryToList(obj);
                        }
                    }
                });
                this.$modal.closeLoading();
                // 关闭查询弹出框
                this.searchProductCodeCancel();
            },
            /** ⑧ 点击关闭查询弹出框 **/
            searchProductCodeCancel() {
                this.searchProductCodeDialogOpen = false;
            },
            /* ※※ 查询 产品 相关方法 end ※※ */
            deleteEntry(idx){
                this.settlebillEntryList.splice(idx, 1);
                // 行号重新编排
                for(let i=0 ; i<this.settlebillEntryList.length ; i++){
                    this.settlebillEntryList[i].lineNo = i+1;
                }
                this.refreshFee();
            },
            /**
             * 深拷贝一个对象
             **/
            copyObj(obj){
                let newObj = JSON.parse(JSON.stringify(obj));
                return newObj;
            },
            /**
             * 刷新合计金额
             */
            refreshFee(){
                // 1. 待销金额(含税)
                let fee = 0;
                // 2. 待销金额(不含税)
                let feeWithoutTax = 0;
                // 3. 税额
                let tax = 0;
                this.settlebillEntryList.forEach(function(item, index) {
                    fee =  parseFloat(Number(item.amount ? item.amount : 0).toFixed(8)) + parseFloat(Number(fee).toFixed(8));
                    feeWithoutTax = parseFloat(Number(item.withoutAmount ? item.withoutAmount : 0).toFixed(8)) + parseFloat(Number(feeWithoutTax).toFixed(8));
                    tax = parseFloat(Number(item.tax ? item.tax : 0).toFixed(8)) + parseFloat(Number(tax).toFixed(8));
                });
                this.detailForm.fee = fee;
                this.detailForm.feeWithoutTax = feeWithoutTax;
                this.detailForm.tax = tax;
            },
            /**
             * 修改拆分金额（不含税）
             */
            changeWithoutAmount(row){
                if(row.withoutAmount > row.orgWithoutAmount){
                    this.$modal.msgError("拆分金额(不含税)不能大于待拆金额(不含税)");
                    return;
                }
                // 1. 计算拆分数量 = 拆分金额（不含税）/ 单价（不含税） = withoutAmount/withoutPrice
                row.qty = Number(row.withoutAmount/row.withoutPrice).toFixed(8);
                // 2. 计算拆分金额（不含税） = 拆分金额（含税）* （1+税率） = withoutAmount*(1+taxRate)
                row.amount = Number(row.withoutAmount*((row.kpProductTax/100)+1)).toFixed(8);
                // 3. 刷新合计
                this.refreshFee();
            },
            /**
             * 修改拆分金额（含税）
             */
            changeAmount(row){
                if(row.amount > row.orgAmount){
                    this.$modal.msgError("拆分金额(含税)不能大于待拆金额(含税)");
                    row.amount = row.orgAmount;
                    return;
                }
                // 1. 计算拆分数量 = 拆分金额（含税）/ 单价（含税） = amount/price
                row.qty = Number(row.amount/row.price).toFixed(8);
                // 2. 计算拆分金额（不含税） = 拆分金额（含税）/ （1+税率） = amount/(1+taxRate)
                row.withoutAmount = Number(row.amount/((row.kpProductTax/100)+1)).toFixed(8);
                row.tax = Number(row.amount - row.withoutAmount).toFixed(8);
                // 3. 刷新合计
                this.refreshFee();
            },
            /**
             * 修改拆分折扣金额(不含税)
             */
            changeWithoutDiscountAmount(row){
                if(row.withoutDiscountAmount > row.orgWithoutDiscountAmount){
                    this.$modal.msgError("拆分折扣金额(不含税)不能大于待拆分折扣金额(不含税)");
                    return;
                }
                // 1. 计算拆分折扣金额（含税） = 拆分折扣金额(不含税) * （1+税率） = withoutDiscountAmount/(1+taxRate)
                row.discountAmount = Number(row.withoutDiscountAmount/((row.kpProductTax/100)+1)).toFixed(8);
            },
            /**
             * 修改拆分折扣金额(含税)
             */
            changeDiscountAmount(row){
                if(row.discountAmount > row.orgDiscountAmount){
                    this.$modal.msgError("拆分折扣金额(含税)不能大于待拆分折扣金额(含税)");
                    return;
                }
                // 1. 计算拆分折扣金额(含税) = 拆分折扣金额（含税）/ （1+税率） = discountAmount/(1+taxRate)
                row.withoutDiscountAmount = Number(row.discountAmount/((row.kpProductTax/100)+1)).toFixed(8);
            },
            /** 选择开票产品 */
            selectKpProductChange(row){
                if(row.kpProductCode){
                    row.productList.forEach((product, index) => {
                        if(product.productCode === row.kpProductCode){
                            row.kpProduct = product;
                        }
                    });
                    row.kpProductTax = row.kpProduct.taxRate;
                    row.kpProductUnit = row.kpProduct.unit;
                    row.kpProductTaxName = row.kpProduct.taxName;
                    row.kpProductTaxCode = row.kpProduct.taxCode;
                    // 2.刷新税率，刷新金额
                    row.withoutDiscountAmount = Number(row.discountAmount/((row.kpProductTax/100)+1)).toFixed(8);
                    row.withoutAmount = Number(row.amount/((row.kpProductTax/100)+1)).toFixed(8);
                    row.tax = Number(row.amount - row.withoutAmount).toFixed(8);
                } else {
                    row.kpProduct = {};
                    row.kpProductTax = 0;
                    row.kpProductUnit = '';
                    row.kpProductTaxName = '';
                    row.kpProductTaxCode = '';
                    // 2.刷新税率，刷新金额
                    row.withoutDiscountAmount = 0;
                    row.withoutAmount = 0;
                    row.tax = 0;
                }
                // 3. 刷新合计
                this.refreshFee();
            },
            /** 刷新某物料对应的产品列表 */
            refreshProductList(row){
                // 查询该物料对应的产品列表，放入 productList 属性
                getProductListByMaterialCode(row.productCode.replace(/\//g, '€')).then(response => {
                    row.productList = response;
                }).catch(() => {
                    console.error("无法查询到开票产品");
                    return;
                });
                row.kpProduct = {};
                row.kpProductCode = null;
                row.kpProductTax = 0;
                row.kpProductUnit = '';
                row.kpProductTaxName = '';
                row.kpProductTaxCode = '';
                // 2.刷新税率，刷新金额
                row.withoutDiscountAmount = 0;
                row.withoutAmount = 0;
                row.tax = 0;
                // 3. 刷新合计
                this.refreshFee();
            },
            /**
             * 保存拆分为待开票
             */
            saveAsInvoice(){
                let that = this;
                if(this.settlebillEntryList.length == 0){
                    that.$modal.msgError("整张订单的金额，不能小于或等于0");
                    return;
                }
                this.settlebillEntryList.forEach(function(item, index) {
                    if(!item.kpProduct){
                        that.$modal.msgError("[" + item.productName + "]需要选择对应开票产品");
                        return;
                    }
                    if(item.amount > item.orgAmount){
                        that.$modal.msgError("[" + item.productName + "]拆分金额(含税)不能大于待拆金额(含税)");
                        return;
                    }
                    // if(item.withoutAmount > item.orgWithoutAmount){
                    //     this.$modal.msgError(item.productName + "拆分金额(不含税)不能大于待拆金额(不含税)");
                    //     return;
                    // }
                    // if(item.withoutDiscountAmount > item.orgWithoutDiscountAmount){
                    //     that.$modal.msgError("[" + item.productName + "拆分折扣金额(不含税)不能大于待拆分折扣金额(不含税)");
                    //     return;
                    // }
                    that.$modal.loading("正在初始化，请稍候...");
                    if(item.discountAmount > item.orgDiscountAmount){
                        that.$modal.msgError("[" + item.productName + "]拆分折扣金额(含税)不能大于待拆分折扣金额(含税)");
                        return;
                    }
                });
                that.detailForm.tscSettlebillEntryList = that.settlebillEntryList;
                saveAsSalInvoice(that.detailForm).then(response => {
                    that.$modal.closeLoading();
                    that.$modal.msgSuccess("保存成功");
                    that.init(that.settleId);
                    //关闭当前页
                    this.$store.dispatch("tagsView/delView", this.$route);
                    // 需要跳转至
                    this.$router.push({path:'/sal/saltobeInvoice/tobe'})
                }).catch(() => {
                    that.$modal.closeLoading();
                    return;
                });;
            }
        }
    }
</script>
